package com.smfx.yxt;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.CloneUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.smfx.yxt.model.StudentFruits;
import com.smfx.yxt.model.StudentSchoolPrize;
import com.smfx.yxt.page.OrderBy;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.ScoreSummaryQueryVO;
import com.smfx.yxt.reqVo.WeekCommentQueryVO;
import com.smfx.yxt.service.IScoreSummaryService;
import com.smfx.yxt.service.IStudentFruitsService;
import com.smfx.yxt.service.IStudentSchoolPrizeService;
import com.smfx.yxt.service.IStudentWeekCommentService;
import com.smfx.yxt.task.WeekCommentJob;
import com.smfx.yxt.utils.DateUtil;
import com.smfx.yxt.view.StudentScoreView;
import com.smfx.yxt.view.StudentWeekCommentView;

public class SchoolCommentWeekService extends BaseTest {

	@Autowired
	WeekCommentJob weekCommentJob;
	@Autowired
	private IStudentWeekCommentService studentWeekCommentService;
	@Autowired
	private IScoreSummaryService scoreSummaryService;
	@Autowired
	private IStudentFruitsService studentFruitsService;
	@Autowired
	private IStudentSchoolPrizeService studentSchoolPrizeService;
	
	public static void main(String[] args) {
		String output = "F:/yxtfile/studentGroupup/2014/1/艾柏文/成长足迹.pdf";
		String inUrl = "F:/yxtfile/studentGroupup/2014/1/艾柏文";
		Document document = null;
		try {
			File file = new File(inUrl);
			File[] files = file.listFiles();
			File outFile = new File(output);
			if(!outFile.exists()) {
				outFile.createNewFile();
			}
			if(files != null && files.length > 0) {
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
				document = new Document();
				PdfCopy copy = new PdfCopy(document, out);
		        document.open();
				for(File file2 : files) {
					try {
						PdfReader reader = new PdfReader(file2.getPath());
						int n = reader.getNumberOfPages();  
		                for (int j = 1; j <= n; j++) {  
		                    document.newPage();  
		                    PdfImportedPage page = copy.getImportedPage(reader, j);  
		                    copy.addPage(page);  
		                }
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(document != null) {
				document.close();
			}
		}
	}
	
	@Test
	public void noticeParent() {
		//weekCommentJob.noticeParent();
		//weekCommentJob.remaindTeacher();
	}
	
	@Test 
	public void pdf() {
		try {
			//createWeekPdf(1, 595);
			//createStudentScorePdf(2015, 2018, 595);
			createStudentScorePdf();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void createWeekPdf(Integer schoolId, Integer studentId) {
		WeekCommentQueryVO vo = new WeekCommentQueryVO();
		vo.setSchoolId(schoolId);
		vo.setStudentId(studentId);
		List<StudentWeekCommentView> rows = studentWeekCommentService.selectStudentCommentList(vo);
		//每一条数据代表一个pdf表格
        List<PdfReader> list = new ArrayList<>();
        String tempFile = "C:/Users/hqm/Desktop/每周点评_temp.pdf";
        String realFile = "C:/Users/hqm/Desktop/每周点评.pdf";
        try {
        	File file = new File(tempFile);
        	if(!file.exists()) {
        		file.createNewFile();
        	}
        	FileOutputStream outputStream = new FileOutputStream(file);
            //不确定数据有多少，所以要无限循环
            while (true) {
                String realPath = "C:/Users/hqm/Desktop"; //request.getSession().getServletContext().getRealPath("/");//项目路径
                //使用微软雅黑字体显示中文
                //BaseFont chinessFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                PdfReader reader = new PdfReader(realPath + "/weekCommentTemplate1.pdf");//读取
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                PdfReader pdfReader = null;
            	//回去填充pdf的对象
                PdfStamper ps = new PdfStamper(reader, bos);
                AcroFields s = ps.getAcroFields();
                s.setField("studentName", rows.get(0).getStudentName());
                s.setField("termName", rows.get(0).getTermName());
                s.setField("teacherName", rows.get(0).getTeacherName());
                s.setField("weekDate", rows.get(0).getStartDate() + " / " + rows.get(0).getEndDate());
                s.setField("weekNo", String.valueOf(rows.get(0).getWeekNo()));
                s.setField("teacherComment", rows.get(0).getTeacherCommentContent());
                if(StringUtils.isNotBlank(rows.get(0).getStudentCommentContent())) {
                	String studentComment = rows.get(0).getStudentCommentContent();
                	studentComment = studentComment.replaceAll("a\\|a", "：").replaceAll("b,b", "。");
                	s.setField("studentComment", studentComment);
                }
                if(StringUtils.isNotBlank(rows.get(0).getParentCommentContent())) {
                	s.setField("parentComment", rows.get(0).getParentCommentContent());
                }
                if(StringUtils.isNotBlank(rows.get(0).getTeacherCommentType())) {
                	String[] typeArry = rows.get(0).getTeacherCommentType().replace("|", "：").split(",");
                	for(int i = 0; i < typeArry.length; i++) {
                		s.setField("teacherStar" + (i + 1), typeArry[i] + "星");
                	}
                }
                //热爱劳动|5,学习态度|3,参与活动|4,孝敬长辈|5
                if(StringUtils.isNotBlank(rows.get(0).getParentCommentType())) {
                	String[] typeArry = rows.get(0).getParentCommentType().replace("|", "：").split(",");
                	for(int i = 0; i < typeArry.length; i++) {
                		s.setField("parentStar" + (i + 1), typeArry[i] + "星");
                	}
                }else {
                	s.setField("parentStar1", "热爱劳动：");
                	s.setField("parentStar2", "学习态度：");
                	s.setField("parentStar3", "参与活动：");
                	s.setField("parentStar4", "孝敬长辈：");
                }
                ps.close();
                pdfReader = new PdfReader(bos.toByteArray());
                list.add(pdfReader);
                rows.remove(0);
                if(rows.size() == 0) {
                	break;
                }
            }
	        //上面已经获得了pdf的每一页，这里我只需要合并成为一个pdf，然后返回
	        Document document = new Document();
	        PdfCopy copy = new PdfCopy(document, outputStream);
	        document.open();
	        for (int k = 0; k < list.size(); k++) {
	            PdfReader pdfReader = list.get(k);
	            document.newPage();
	            copy.addDocument(pdfReader);
	        }
	        copy.close();
			addImage(tempFile, realFile,"C:/Users/hqm/Desktop/seal.png");
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	public void createStudentScorePdf(Integer grade, Integer termKey, Integer studentId){
		Document pdfDocument = new Document(PageSize.A4,50,50,50,150);
		String tempFile = "C:/Users/hqm/Desktop/学生成绩_temp.pdf";
		String realFile = "C:/Users/hqm/Desktop/学生成绩.pdf";
		try {
			List<Integer> list = new ArrayList<>();
			for(int i = 0; i <= 5; i++) {
				if((grade + i) >= termKey) {
					break;
				}
				list.add(grade + i);
			}
			ScoreSummaryQueryVO vo = new ScoreSummaryQueryVO();
			vo.setScoreList(list);
			vo.setStudentId(studentId);
			vo.setOrder("asc");
			List<StudentScoreView> scoreList = scoreSummaryService.selectStudentScore(vo);
			File file = new File(tempFile);
        	if(!file.exists()) {
        		file.createNewFile();
        	}
			//构建一个PDF文档输出流程
        	OutputStream pdfFileOutputStream = new FileOutputStream(file);
        	PdfWriter.getInstance(pdfDocument,pdfFileOutputStream);
        	pdfDocument.open();
			//设置中文字体和字体样式
	        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
	        Font f8 = new Font(bfChinese, 8, Font.NORMAL);
	        String[] columnTableContent = new String[]{"学期","考试","语文","年级人平均分","英语","年级人平均分","数学","年级人平均分","总分"};
	        //创建一个N列的表格控件
	        PdfPTable pdfTable = new PdfPTable(columnTableContent.length);
	        //设置表格占PDF文档100%宽度
	        pdfTable.setWidthPercentage(100);
	        //水平方向表格控件左对齐
	        pdfTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
	        //创建一个表格的表头单元格
	        PdfPCell pdfTableHeaderCell = new PdfPCell();
	        //设置表格的表头单元格颜色
	        pdfTableHeaderCell.setBackgroundColor(new BaseColor(213, 141, 69));
	        pdfTableHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
	        for(String tableHeaderInfo : columnTableContent){
	        	pdfTableHeaderCell.setPhrase(new Paragraph(tableHeaderInfo, f8));
	        	pdfTable.addCell(pdfTableHeaderCell);
	        }
	        //创建一个表格的正文内容单元格
	        PdfPCell pdfTableContentCell = new PdfPCell();
	        pdfTableContentCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
	        pdfTableContentCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
	        int submitAmount = 2000;
	        //表格内容行数的填充
	        for(int i = 0; i < scoreList.size(); i++){
	        	StudentScoreView score = scoreList.get(i);
            	pdfTableContentCell.setPhrase(new Paragraph(score.getTermName(), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	pdfTableContentCell.setPhrase(new Paragraph(score.getExamName(), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getChineseScore()), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	if(score.getScoreAvgList() != null && score.getScoreAvgList().size() >= 1) {
            		pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getScoreAvgList().get(0).getAvgScore()), f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}else {
            		pdfTableContentCell.setPhrase(new Paragraph("", f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}
            	pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getEnglishScore()), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	if(score.getScoreAvgList() != null && score.getScoreAvgList().size() >= 2) {
            		pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getScoreAvgList().get(1).getAvgScore()), f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}else {
            		pdfTableContentCell.setPhrase(new Paragraph("", f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}
            	pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getMathScore()), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	if(score.getScoreAvgList() != null && score.getScoreAvgList().size() >= 3) {
            		pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getScoreAvgList().get(2).getAvgScore()), f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}else {
            		pdfTableContentCell.setPhrase(new Paragraph("", f8));
                	pdfTable.addCell(pdfTableContentCell);
            	}
            	pdfTableContentCell.setPhrase(new Paragraph(String.valueOf(score.getSumScore()), f8));
            	pdfTable.addCell(pdfTableContentCell);
            	//表格内容每写满某个数字的行数时，其内容一方面写入物理文件，另一方面释放内存中存留的内容。
	            if((i % submitAmount)==0){
	            	pdfDocument.add(pdfTable);
	            	pdfTable.deleteBodyRows();
                }else if(i == scoreList.size()){
                	//如果全部类容完毕且又没达到某个行数限制，则也要写入物理文件中。
                	pdfDocument.add(pdfTable);
                	pdfTable.deleteBodyRows();
                }
	        }
	        pdfDocument.add(pdfTable);
	    }catch(Exception e) {
	        e.printStackTrace();
	    }finally {
	    	if(pdfDocument!=null){
        		pdfDocument.close();
        		try {
					addImage(tempFile, realFile,"C:/Users/hqm/Desktop/seal.png");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
		}
	}

	public boolean createStudentScorePdf(){
		Document pdfDocument = new Document(PageSize.A4,50,50,20,150);
		String tempFile = "C:/Users/hqm/Desktop/学生成果_temp.pdf";
		String realFile = "C:/Users/hqm/Desktop/学生成果.pdf";
		try {
			Page<StudentFruits> page = new Page<>();
			page.setPageSize(20);
			List<OrderBy> orders = new ArrayList<>();
			orders.add(new OrderBy("学期id"));
			page.setSorts(orders);
			List<StudentFruits> fruits = studentFruitsService.selectListByPage(page);
			List<StudentSchoolPrize> prizes = studentSchoolPrizeService.selectStudentPrizeList(1);
			if(CollectionUtils.isEmpty(fruits) && CollectionUtils.isEmpty(prizes)) {
				return true;
			}
			File file = new File(tempFile);
        	if(!file.exists()) {
        		file.createNewFile();
        	}
			//构建一个PDF文档输出流程
        	OutputStream pdfFileOutputStream = new FileOutputStream(file);
        	PdfWriter.getInstance(pdfDocument,pdfFileOutputStream);
        	pdfDocument.open();
			//设置中文字体和字体样式
	        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
	        Font f8 = new Font(bfChinese, 8, Font.NORMAL);
	        Font f10 = new Font(bfChinese, 10, Font.BOLD);
	        f10.setColor(new BaseColor(250, 250, 250));
	        Font f16 = new Font(bfChinese,16,Font.BOLD); //加粗
	        Font firsetTitleFont = new Font(bfChinese,22,Font.BOLD); //一级标题
	        Paragraph p1 = new Paragraph("同学的成果", firsetTitleFont);
	        p1.setAlignment(Element.ALIGN_CENTER);
	        pdfDocument.add(p1);
	        if(!CollectionUtils.isEmpty(prizes)) {
	        	Paragraph ph = new Paragraph(); 
	        	ph.setSpacingBefore(40);
	        	ph.setSpacingAfter(20);
	        	ph.add(new Chunk("获奖成果", f16));
	        	pdfDocument.add(ph);
	            String[] columnTableContent = new String[]{"竞赛名称","参赛子项目","作品名称","获奖级别","获奖等第","授奖单位","指导教师","获奖时间"};
		        //创建一个N列的表格控件
		        PdfPTable pdfTable = new PdfPTable(columnTableContent.length);
		        //设置表格占PDF文档100%宽度
		        pdfTable.setWidthPercentage(100);
		        //水平方向表格控件左对齐
		        pdfTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		        //创建一个表格的表头单元格
		        PdfPCell pdfTableHeaderCell = new PdfPCell();
		        //设置表格的表头单元格颜色
		        pdfTableHeaderCell.setBackgroundColor(new BaseColor(213, 141, 69));
		        pdfTableHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		        pdfTableHeaderCell.setCalculatedHeight(150);
		        for(String tableHeaderInfo : columnTableContent){
		        	pdfTableHeaderCell.setPhrase(new Paragraph(tableHeaderInfo, f10));
		        	pdfTableHeaderCell.setMinimumHeight(20);
		        	pdfTable.addCell(pdfTableHeaderCell);
		        }
		        //创建一个表格的正文内容单元格
		        PdfPCell pdfTableContentCell = new PdfPCell();
		        pdfTableContentCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		        pdfTableContentCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		        //表格内容行数的填充
		        for(int i = 0; i < fruits.size(); i++){
		        	StudentFruits score = fruits.get(i);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getCompetitionName(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getTakeSubProject(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getWorksName(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getAwardGrade(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getAwardLevel(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getAwardCompany(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(score.getGuideTeacher(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(DateUtil.dateToStr(score.getAwardTime(), DateUtil.DATE_FORMAT1), f8));
	            	pdfTable.addCell(pdfTableContentCell);
		        }
		        pdfDocument.add(pdfTable);
	        }
	        
	        if(!CollectionUtils.isEmpty(prizes)) {
	        	Paragraph ph = new Paragraph(); 
	        	ph.setSpacingBefore(40);
	        	ph.setSpacingAfter(20);
	        	ph.add(new Chunk("校内荣誉", f16));
	        	pdfDocument.add(ph);
	            String[] columnTableContent = new String[]{"学期","校内荣誉"};
		        //创建一个N列的表格控件
		        PdfPTable pdfTable = new PdfPTable(columnTableContent.length);
		        //设置表格占PDF文档100%宽度
		        pdfTable.setWidthPercentage(100);
		        //水平方向表格控件左对齐
		        pdfTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		        //创建一个表格的表头单元格
		        PdfPCell pdfTableHeaderCell = new PdfPCell();
		        //设置表格的表头单元格颜色
		        pdfTableHeaderCell.setBackgroundColor(new BaseColor(213, 141, 69));
		        pdfTableHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		        for(String tableHeaderInfo : columnTableContent){
		        	pdfTableHeaderCell.setPhrase(new Paragraph(tableHeaderInfo, f10));
		        	pdfTableHeaderCell.setMinimumHeight(20);
		        	pdfTable.addCell(pdfTableHeaderCell);
		        }
		        //创建一个表格的正文内容单元格
		        PdfPCell pdfTableContentCell = new PdfPCell();
		        pdfTableContentCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		        pdfTableContentCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		        //表格内容行数的填充
		        for(int i = 0; i < prizes.size(); i++){
		        	StudentSchoolPrize prize = prizes.get(i);
		        	pdfTableContentCell.setPhrase(new Paragraph(prize.getTermName(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
	            	pdfTableContentCell.setPhrase(new Paragraph(prize.getPrizeName(), f8));
	            	pdfTable.addCell(pdfTableContentCell);
		        }
		        pdfDocument.add(pdfTable);
	        }
	
	        return true;
	    }catch(Exception e) {
	        e.printStackTrace();
	    }finally {
	    	if(pdfDocument!=null){
        		pdfDocument.close();
        		try {
					addImage(tempFile, realFile,"C:/Users/hqm/Desktop/seal.png");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}
        	}
		}
		return false;
	}
	
	public static  void addImage(String file, String output, String imgPath) throws Exception{
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(output)));
		PdfReader reader = new PdfReader(file);
		PdfStamper stamper = new PdfStamper(reader, out);
		int total = reader.getNumberOfPages();
		try {
			Image image = Image.getInstance(imgPath);
			image.setAbsolutePosition(450, 50);
			image.scaleToFit(160, 70);
			for(int i = 1; i <= total; i++) {
				PdfContentByte content= stamper.getOverContent(i);// 在内容上方加水印
				content.addImage(image);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			stamper.close();
			reader.close();
			new File(file).deleteOnExit();
		}
		
	}

}

